
import re
import os
import string
import pepe.p_utils.outlook_webscraper as o

def pp_mime(x):
    x = re.sub('%20', ' ', x)
    x = re.sub('%C5%A1', 's', x)
    x = re.sub('%C3%AD', 'i', x)
    x = re.sub('%C3%A1', 'a', x)
    x = re.sub('%C5%99', 'r', x)
    return x

remove_html_tags = lambda x: re.sub('<([^!>]([^>]|\n)*)>', '', x)   # remove html tags 

def pp_msg(data):
    """ """
    data = remove_html_tags(data)
    data = re.sub('\n{2,}', '\n', data)
    data = re.sub('\n', '\n\t', data)
    data = re.sub(' {2,}', ' ', data)
    return data

def list_inbox(server='', dusern='', passwd=''):
    """ """
    m = o.OutlookWebScraper(server, dusern, passwd)
    try:
        m.login()
        # Display IDs of messages in the inbox.
        #print m.inbox()
        
        #of = open('dtmail.out', 'w')
        for msid in m.inbox():
            # print message ID
            print pp_mime(msid)
            # print From field

            # for big messages it loads whole message ... have to wait
            '''
            for row in string.split(m.get_message(msid), '\n'):
                if row[:4] in ('From', 'Date'):
                    print "\t%s" % (row)
            '''
            
            """
            of.write("%s\n" % (p20(msid)))
            of.write("\t - - \n")
            of.write("\t%s \n" % 
                        (pp_msg(m.get_message(msid)
                                )
                        )
                    )
            of.write("\t - - \n")
            """
        #of.close()
    except IOError:
        print 'Network error ... try later.'

def rfile(inputfile):
    """ read (small) data from file
    """
    if os.path.exists(inputfile):
        p = open(inputfile, 'r').read()
        return p
    else:
        return False

def main():
    """ """
    opts = {  'server':'https://emamail.deloitte.com/owa'
            , 'dusern':'atrema/vpresovsky'
            , 'passwd':''
            }

    if rfile('c:/aft/ERASE-THIS'): 
        opts['passwd'] = rfile('c:/aft/ERASE-THIS')
    else:
        print 'Password file (c:/aft/ERASE-THIS) not found.'
    if opts['passwd'] == '':
        #print "%s" % (opts['dusern'])
        opts['passwd'] = raw_input("Enter password for %s : " % (opts['dusern']))
        of = open('c:/aft/ERASE-THIS', 'w')
        of.write(opts['passwd'])
        of.close()

    print ""
    
    list_inbox(   server = opts['server']
                , dusern = opts['dusern']
                , passwd = opts['passwd'])

main()